/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.server.social;

import com.icee.myth.common.messageQueue.DBMessageQueue;
import com.icee.myth.log.GameLogger;
import com.icee.myth.log.message.FileDebugGameLogMessage;
import com.icee.myth.log.message.builder.GameLogMessageBuilder;
import com.icee.myth.protobuf.InternalCommonProtocol.DBRelationProto;
import com.icee.myth.server.GameServer;
import com.icee.myth.server.actor.Human;
import com.icee.myth.server.message.dbMessage.builder.MapDBMessageBuilder;
import com.icee.myth.server.notification.NotifySystem;
import com.icee.myth.server.notification.message.BeAddFriendNotificationMessage;
import com.icee.myth.server.social.message.AddRelationShipSocialMessage;
import com.icee.myth.server.social.message.GetInfoSocialMessage;
import com.icee.myth.server.social.message.RemoveRelationShipSocialMessage;
import com.icee.myth.utils.Consts;

import java.util.Iterator;
import java.util.TreeMap;

/**
 * 注意: 默认组号为0号，不需要记入组列表中
 * @author liuxianke
 */
public class Social {
    public TreeMap<Integer, Relation> relations = new TreeMap<Integer, Relation>(); // key为玩家id，值为玩家的关系

    private long lastRefreshTime;

    public Social() {
    }
    
    public void init(long curTime) {
        lastRefreshTime = curTime;
    }

    public Relation getRelation(int playerId) {
        Relation relation = relations.get(playerId);
        if (relation == null) {
            relation = new Relation(playerId);
            relations.put(playerId, relation);

            // 向数据库获取玩家关系数据
            DBMessageQueue.queue().offer(MapDBMessageBuilder.buildGetRelationDBMessage(playerId));
        }

        return relation;
    }

    public void loadRelation(Human human) {
        int playerId = human.id;
        Relation relation = getRelation(playerId);

        if (relation.inited) {
            human.setRelation(relation);
        } else {
            // 将加载请求放入等待消息队列
            relation.addMessage(new GetInfoSocialMessage(playerId));
        }
    }

    public void addRelationShip(int follower, int befollower) {
        Relation relation1 = getRelation(befollower);

        if (relation1.inited) {
            Relation relation2 = relations.get(follower);
            if (relation2 != null) {
                if (relation2.inited) {
                    relation2.addConcern(befollower);
                    relation1.addFollower(follower);

                    // 若befollower未将follower加为好友，通知befollower有follower加他为好友
                    if (!relation1.concerns.contains(follower)) {
                        BriefPlayerInfo briefPlayerInfo = GameServer.INSTANCE.briefPlayerInfos.get(follower);
                        NotifySystem.INSTANCE.sendNote(befollower, new BeAddFriendNotificationMessage(follower, relation2.human.name, briefPlayerInfo.leaderCardId, briefPlayerInfo.leaderCardLevel), true);
                    }
                } else {
                    GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                            FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                            "Set follower[" + follower +"] to befollower["+befollower+"] relation ship error because follower relation object not inited."));
                }
            } else {
                GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                        FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                        "Set follower[" + follower +"] to befollower["+befollower+"] relation ship error because follower relation object not found."));
            }
        } else {
            // 将建立好友关系请求放入等待消息队列
            relation1.addMessage(new AddRelationShipSocialMessage(follower, befollower));
        }
    }

    public void removeRelationShip(int follower, int concern) {
        Relation relation1 = getRelation(concern);

        if (relation1.inited) {
            Relation relation2 = relations.get(follower);
            if (relation2 != null) {
                if (relation2.inited) {
                    relation2.removeConcern(concern);
                    relation1.removeFollower(follower);
                } else {
                    GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                            FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                            "Remove follower[" + follower +"] to concern["+concern+"] relation ship error because follower relation object not inited."));
                }
            } else {
                GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                        FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                        "Remove follower[" + follower +"] to concern["+concern+"] relation ship error because follower relation object not found."));
            }
        } else {
            // 将解除好友关系请求放入等待消息队列
            relation1.addMessage(new RemoveRelationShipSocialMessage(follower, concern));
        }
    }

    public void setRelationData(int playerId, DBRelationProto relationProto, boolean foundPlayer) {
        Relation relation = relations.get(playerId);
        if (relation != null) {
            if (foundPlayer) {
                relation.init(relationProto);
            } else {
                relation.handleMessages();
                relations.remove(playerId);
                
                GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                        FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                        "Set Player[" + playerId +"] relation data error because player not found."));
            }
        } else {
            GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                    FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                    "Set Player[" + playerId +"] relation data error because relation object not found."));
        }
    }
    
    /**
     * 定期保存和清理（每5分钟将修改过的关系存入数据库，将过期且不在线玩家关系从内存关系表中清除）
     * @param curTime
     */
    public void refresh(long curTime) {
        if (curTime - lastRefreshTime >= Consts.MILSECOND_5MINITE) {
            lastRefreshTime = curTime;
            for (Iterator<Relation> itor = relations.values().iterator(); itor.hasNext(); ) {
                Relation relation = itor.next();

                if (relation.inited) {
                    if (relation.dirty) {
                        // TODO: 存盘
                        DBMessageQueue.queue().offer(MapDBMessageBuilder.buildSaveRelationDBMessage(relation.id, relation.buildDBRelationProto()));
                        relation.dirty = false;
                    }

                    if ((relation.human == null) && (curTime - relation.lastVisitTime >= Consts.CLEAR_RELATION_TIME)) {
                        // 删除过期数据
                        itor.remove();
                    }
                }
            }
        }
    }

}
